<?php

/**
 * Created by PhpStorm.
 * Author: netman
 * Time: 2023/9/11 11:06
 * Desc:
 */
class Service_Api_Payqrcode extends Contract_Api_Payqrcode
{
    use Trait_Api_Payqrcode;
    use Trait_Api_Image;
    use Trait_Api_Content;
    use Trait_Api_Response;
    /**
     * 类型ID
     */
    const TYPE_ID = 15;

    public function create_order(array $params): array
    {

        $member_info = $params['member_info'] ?? array();
        $info = DB::select()->from('pay_qrcode')->where('id', '=', $params['pay_qrcode_id'])
            ->where('status','=', 2)
            ->execute()
            ->current();
        if (empty($info)) {
            throw new Exception("支付二维码不存在");
        }
        // 初始化订单数据
        $order = $this->make_order_data($params, $info, $member_info);
        $order['price']   = Num::format($params['price'], 2);

        // 添加订单
        $out = Model_Api_V2_Order::add_order($order, 'Model_Payqrcode', $order);
        if (!$out['status']) {
            throw new Exception($out['msg']);
        }

        // 订单添加成功
        $order_info            = Model_Member_Order::order_info($order['ordersn']);
        $order_id              = $order_info['id'];
        $order_info['orderid'] = $order_id;
        //添加扩展表,后面需要新增内容可以在此表扩展
        $qrcode_order = [
            'pay_qrcode_id' => $params['pay_qrcode_id'],
            'order_id' => $order_id,
            'qrcode_type' => $info['type'],
            'merchant' => $info['title']
        ];
        DB::insert('pay_qrcode_order')->columns(array_keys($qrcode_order))->values($qrcode_order)->execute();

        // 预订事件
        Hook::trigger('order_created', $order_info);

        // 返回订单信息
        $filter_keys = array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status');
        return $this->filter_data($filter_keys, $order_info);
    }




    /**
     * 获取支付二维码信息
     * @param $params
     * @return array
     * @throws Exception
     * User: netman
     * Date: 2023/11/28 10:38
     */
    function get_payqrcode_info($params): array
    {
        $pay_qrcode_id = (int)$params['pay_qrcode_id'];
        $pay_info = DB::select()->from('pay_qrcode')->where('id', '=', $pay_qrcode_id)->execute()->current();
        if (!$pay_info) {
            throw new Exception('支付二维码不存在');
        }
        $pay_info['amount'] = $pay_info['amount'] ? Num::format((float)$pay_info['amount'],2) : 0;
        $pay_info['amount'] = $pay_info['amount'] == 0.00 ? "" : $pay_info['amount'];
        return $pay_info;
    }
}